import { View, Image, Text } from "@tarojs/components";
import Taro, { useDidShow, useDidHide, eventCenter } from "@tarojs/taro";
import React, { useState, useEffect } from "react";
import { Button, NoticeBar, Avatar, Dialog } from "@nutui/nutui-react-taro";
import { ArrowRight } from "@nutui/icons-react-taro";
import LoginPopupProvider from "../../components/LoginPopup/index";
import "./index.less";
import avatarIcon from "../../assets/avtar.png";

const USER_IMAGE_DEFAULT = avatarIcon;
const nickName_DEFAULT = "获取昵称";

const TOKEN_KEY = "token";
function my() {
  const [userInfo, setUserInfo] = useState({
    nickName: nickName_DEFAULT,
    avatar: { url: USER_IMAGE_DEFAULT },
    phoneNumber: "",
    id: 0,
  });

  useDidHide(() => {
    console.log("useDidHide  my");

    openLoginPopup(false);
  });

  useDidShow(() => {
    const token = Taro.getStorageSync(TOKEN_KEY);
    const userInfo = Taro.getStorageSync("userInfo");
    console.log(userInfo, token, "userInfo");

    if (userInfo.phoneNumber && token) {
      setUserInfo(userInfo);
    } else {
      setUserInfo({
        nickName: nickName_DEFAULT,
        avatar: { url: USER_IMAGE_DEFAULT },
        phoneNumber: "",
        id: 0,
      });
      openLoginPopup();
    }
  });

  const isEmptyObject = (obj) => {
    return Object.keys(obj).length === 0 && obj.constructor === Object;
  };

  useEffect(() => {
    eventCenter.on("updateUserInfo", (data) => {
      console.log(data, "updateUserInfo");
      if (isEmptyObject(data)) {
        data = {
          nickName: nickName_DEFAULT,
          avatar: { url: USER_IMAGE_DEFAULT },
          phoneNumber: "",
          id: 0,
        };
      }
      setUserInfo(data);
    });

    return () => {
      eventCenter.off("updateUserInfo");
    };
  }, []);

  const navigateToPage = (url) => {
    Taro.navigateTo({ url });
  };

  const handleNavigation = (page) => {
    if (!userInfo.phoneNumber) {
      Taro.showToast({
        title: "请先登录账号",
        icon: "none",
      });
      openLoginPopup(true);
      return;
    }
    navigateToPage(page);
  };

  const navigationMap = {
    订单记录: "/pages/buyList/index",
    开票记录: "/pages/invoiceList/index",
    用户协议: "/pages/role/index",
    隐私协议: "/pages/privacy/index",
    审批内容: "/pages/Approval/index",
  };

  const openLoginPopup = (status = true) => {
    eventCenter.trigger("showLogin", status);
  };

  const goToUserInfo = () => {
    Taro.navigateTo({ url: "/pages/userInfo/index" });
  };

  return (
    <View className="home">
      <NoticeBar content={"网签小程序平台"} />
      <View className="main-content flex flex-column g-6">
        <View>
          {userInfo.phoneNumber ? (
            <View className="tarImage_loagin" onClick={goToUserInfo}>
              <View className="info-content">
                <p className="info-content__input">
                  {userInfo.nickName || nickName_DEFAULT}
                </p>
                <Text className="info-content__phone">
                  手机号：{userInfo.phoneNumber}
                </Text>
              </View>

              <View className="info-content__btn-container">
                <Button className="info-content__btn" />
                <Image
                  src={userInfo.avatar?.url || USER_IMAGE_DEFAULT}
                  className="info-content__avatar"
                />
              </View>
            </View>
          ) : (
            <View className="tarImage">
              <Avatar size="large" src={USER_IMAGE_DEFAULT} />
              <Button
                color="primary"
                shape="round"
                onClick={() => {
                  openLoginPopup(true);
                }}
              >
                登录/注册
              </Button>
            </View>
          )}
        </View>

        {Object.keys(navigationMap).map((item, index) => {
          // 仅在 userInfoId.id 等于 3 或 4 时显示 "审批内容"
          if (
            (item === "审批内容" && (userInfo.id === 3 || userInfo.id === 4)) ||
            item !== "审批内容"
          ) {
            return (
              <View
                key={index}
                className="car_tow"
                onClick={() => handleNavigation(navigationMap[item])}
              >
                <View>{item}</View>
                <ArrowRight />
              </View>
            );
          }
        })}
        {/* 
        {isLogin && (
          <View className="car_tow" onClick={() => setSign(true)}>
            <View>退出登录</View>
            <ArrowRight />
          </View>
        )}

        <Dialog
          title="退出登录"
          visible={sign}
          onConfirm={signOut}
          onCancel={() => setSign(false)}
        >
          确定要退出登录?
        </Dialog> */}
      </View>
      <LoginPopupProvider> </LoginPopupProvider>
    </View>
  );
}

export default my;
